/**
 * @authors tanqichao
 * @date    2017-03-21 13:59:27
 * @module  广告列表
 */

import { Form, Row, Col, Input, Button, Select, Table, Radio, DatePicker, Pagination, Switch } from 'antd';
import { AccessControl } from '../../utils/common';
import RangePicker from '../plugin/rangePicker';
import EditableCell from '../plugin/editableCell';
import { pageSize } from '../../constants';
import React, { Component } from 'react';
import { createForm } from 'rc-form';

import Styles from './adList.less';
import { Link } from 'dva/router';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import moment from 'moment';

moment.locale('zh-cn');

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const FormItem = Form.Item;

class SearchList extends Component {
	constructor(props) {
		super(props);
		this.state = {
			page: 1,
			args: null,
			beginTime: moment().format('YYYY-MM-DD'),
			endTime: moment().format('YYYY-MM-DD')
		}
	}

	// 初始化
	componentDidMount = () => {
		this.search('pre')
  }

	// 分页
  handlePage = (page) => {
  	this.setState({
  		page: page
  	}, () => {
  		this.search()
  	})
  }

  // 切换时间
	handleRangePicker = (beginTime, endTime) => {
		this.setState({
			beginTime: moment(beginTime).format('YYYY-MM-DD'),
			endTime: moment(endTime).format('YYYY-MM-DD')
		}, () => {
			this.search()
		})
	}

	// 搜索
	search = (type) => {
		this.props.form.validateFields((err, values) => {
			let  params = {
				beginTime: this.state.beginTime,
				auditStatus: values.auditStatus,
				endTime: this.state.endTime,
				entName: values.entName || '',
				name: values.name || '',
				status: values.status,
				type: values.type,
				page: this.state.page,
				pageSize: 20
			};
			let adListCheckParams = window.localStorage.getItem('adListCheckParams');
			this.setState({
				args: params
			})
			if(type === 'pre' && adListCheckParams) {
				params = JSON.parse(adListCheckParams);
				console.log(params)
				this.setStatusFun({
					auditStatus: params.auditStatus,
					status: params.status,
					type: params.type,
					name: params.name,
					entName: params.entName
				});
			}
			this.setLocalStorage("adListCheckParams", JSON.stringify(params));
			console.log('%c%s', 'color: #04B894', 'params:' + JSON.stringify(params))
			this.props.dispatch({
				type: 'adList/fetch',
				payload: JSON.stringify(params)
			})
    })
	}
	setResetSearchForm = () => {
		let params = {
			beginTime: this.state.beginTime,
			auditStatus: '',
			endTime: this.state.endTime,
			entName: '',
			name: '',
			status: '',
			type: '',
			page: this.state.page,
			pageSize: 20
		};
			this.props.form.setFieldsValue({'name': ''});
			this.props.form.setFieldsValue({'entName': ''});
			this.props.form.setFieldsValue({'type': ''});
			this.props.form.setFieldsValue({'auditStatus': ''});
			this.props.form.setFieldsValue({'status': ''});
		this.setLocalStorage("adListCheckParams", JSON.stringify(params));
		this.props.dispatch({
			type: 'adList/fetch',
			payload: JSON.stringify(params)
		})
		console.log(params)
	}
	setStatusFun = (params) => {
		for(let key in params) {
			let keyValue = '';
			if(params[key]) {
				keyValue = params[key];
			}
			if(key === 'name') {
				this.props.form.setFieldsValue({'name': keyValue});
			}
			if(key === 'entName') {
				this.props.form.setFieldsValue({'entName': keyValue});
			}
			if(key === 'type') {
				this.props.form.setFieldsValue({'type': keyValue});
			}
			if(key === 'auditStatus'){
				this.props.form.setFieldsValue({'auditStatus': keyValue});
			}
			if(key === 'status') {
				this.props.form.setFieldsValue({'status': keyValue});
			}
		}
	}
	setLocalStorage = (key, data) => {
		if(window.localStorage){
			let storage=window.localStorage;
			storage.setItem(key,data);
		}else {
			alert('该浏览器不支持localStorage');
		}
	}
	// 开关
	switch = (id, checked) => {
		const type = checked ? 'adList/pushOpen' : 'adList/pushClose';
		const params = {
			id: id,
			args: this.state.args
		};
		this.props.dispatch({
			type: type,
			payload: params
		});
	}

	// 修改出价
	onCellChangeFee = (id, key) => {
		const params = {
			id: id,
			fee: key
		};
		this.props.dispatch({
			type: 'adList/updateFee',
			payload: JSON.stringify(params)
		})
  }

  // 修改日预算
	onCellChangeDayBudget = (id, key) => {
		const params = {
			id: id,
			dayBudget: key
		};
		this.props.dispatch({
			type: 'adList/updateDayBudget',
			payload: JSON.stringify(params)
		});
  }

	render () {
		const { getFieldDecorator } = this.props.form;
    const permissionList = this.props.permissions;
		const columns = [{
		  title: '计划ID',
		  dataIndex: 'id',
		  key: 'id'
		}, {
		  title: '广告计划名称',
		  dataIndex: 'name',
		  key: 'name',
		  render: (text, record) => {
		  	return (
		  		<Link to={`/page/ad/detail/${record.id}`}>{text}</Link>
		  	)
		  }
		}, {
		  title: '广告类型',
		  dataIndex: 'type',
		  key: 'type',
		  render: (text, record) => {
				return text === 2 ? '展示广告' : '互动广告'
		  }
		}, {
		  title: '客户公司名称',
		  dataIndex: 'entName',
		  key: 'entName',
		  render: (text, record) => {
		  	return (
		  		<Link to={`/page/manageCustomer?companyName=${record.entName}`}>{text}</Link>
		  	)
		  }
		}, {
		  title: '曝光量',
		  dataIndex: 'exposureCount',
		  key: 'exposureCount'
		}, {
		  title: '点击量',
		  dataIndex: 'clickCount',
		  key: 'clickCount'
		}, {
		  title: '点击率',
		  dataIndex: 'clickRate',
		  key: 'clickRate'
		}, {
		  title: '消耗(元)',
		  dataIndex: 'consumeTotal',
		  key: 'consumeTotal'
		}, {
		  title: '出价(元/次)',
		  dataIndex: 'fee',
		  key: 'fee',
		  render: (text, record, index) => (
		  	AccessControl(permissionList, 'dsp_ad_modify') ?
	        <EditableCell
	          value={text}
						defaultValue={text}
	          onChange={this.onCellChangeFee.bind(this, record.id)}
	        /> : text
      )
		}, {
		  title: '日预算(元/天)',
		  dataIndex: 'dayBudget',
		  key: 'dayBudget',
		  render: (text, record, index) => (
		  	AccessControl(permissionList, 'dsp_ad_modify') ?
	        <EditableCell
	          value={text}
	          onChange={this.onCellChangeDayBudget.bind(this, record.id)}
	        /> : text
      )
		}, {
		  title: '状态',
		  dataIndex: 'statusText',
		  key: 'statusText'
		}, {
		  title: '操作',
		  dataIndex: 'status',
		  key: 'status',
		  render: (text, record) => {
		  	const content = AccessControl(permissionList, 'dsp_ad_modify') ?
		  	(
		  		<Switch
		      	checked={text}
		        checkedChildren={'开'}
		        unCheckedChildren={'关'}
		        onChange={this.switch.bind(this, record.id)}
		      />
		    ) : '';
		    return content;
		  }
		}];

		const pageConfig = {
    	className: "ant-table-pagination",
      total: this.props.totalCount,
      onChange: this.handlePage,
      current: this.state.page,
      pageSize: 20,
		};

		return (
			<Form layout="inline">
				<div className={Styles.search}>
					<Row>
						<Col span={24}>
							<FormItem colon={false} label="广告计划名称" className={Styles.mr45}>
								{getFieldDecorator('name')(
									<Input placeholder="请输入广告计划名称" />
	        			)}
							</FormItem>
							<FormItem colon={false} label="客户名称">
								{getFieldDecorator('entName')(
									<Input placeholder="请输入客户名称" />
	        			)}
							</FormItem>
							<FormItem colon={false} label="广告类型" className={Styles.mr45}>
								{getFieldDecorator('type', {
									initialValue: ''
								})(
									<Select>
			              <Option value="">全部广告</Option>
			              <Option value="1">互动广告</Option>
			              <Option value="2">展示广告</Option>
			            </Select>
	        			)}
							</FormItem>
						</Col>
					</Row>
					<Row className={Styles.mt20}>
						<Col span={24}>
							<FormItem colon={false} label="审核状态" className={Styles.mr45}>
								{getFieldDecorator('auditStatus', {
									initialValue: ''
								})(
									<Select>
			              <Option value="">全部广告</Option>
			              <Option value="0">审核中</Option>
			              <Option value="1">审核通过</Option>
			              <Option value="-1">审核拒绝</Option>
			            </Select>
			          )}
							</FormItem>
							<FormItem colon={false} label="广告状态" className={Styles.mr45}>
								{getFieldDecorator('status', {
									initialValue: ''
								})(
									<Select>
										<Option value="">全部广告</Option>
			              <Option value="10">有效</Option>
			              <Option value="0">暂停</Option>
			              <Option value="1">打开</Option>
			              <Option value="2">余额不足</Option>
			              <Option value="4">非投放日期</Option>
			            </Select>
			           )}
							</FormItem>
							<Button type="primary" size="large" onClick={this.search} className={Styles.searchBtn}>查询</Button>
							<Button type="primary" size="large" onClick={this.setResetSearchForm} className={Styles.searchBtn}>重置</Button>
						</Col>
					</Row>
				</div>
				<Row className={Styles.list}>
					<Col span={24} className={Styles.head}>
						<span className={Styles.subTitle}>所有广告</span>
						{
							AccessControl(permissionList, 'dsp_ad_create') ?
							 	<Button size="large" type="primary" className={Styles.add}><Link to="/page/ad/create"><em>+</em>发布广告</Link></Button> : null
						}
						<div className={Styles.timeFilter}>
							<RangePicker {...this.props} onComplete={this.handleRangePicker} />
						</div>
					</Col>
					<Col span={24}>
						<Table
							className={Styles.pageList}
							rowKey={record => record.id}
							dataSource={this.props.list}
							pagination={pageConfig}
							columns={columns}
						/>
					</Col>
				</Row>
			</Form>
		)
	}
}

export default connect((state) => {
	const { list, totalCount } = state.adList;
	const { permissions } = state.indexPage;
	return {
		list,
		totalCount,
		permissions
	}
})(createForm({})(SearchList))
